package cn.com.pxto.web.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;

import cn.com.pxto.commons.CalendarUtils;
import cn.com.pxto.commons.StringUtils;
import cn.com.pxto.commons.httputil.ParamUtil;
import cn.com.pxto.commons.pagesupport.PageInfo;
import cn.com.pxto.commons.pagesupport.PageUtils;
import cn.com.pxto.commons.propertiesutil.ConfigurationException;
import cn.com.pxto.commons.propertiesutil.Properties;
import cn.com.pxto.global.varables.LogonInfo;
import cn.com.pxto.model.Contact;
import cn.com.pxto.model.Guest;
import cn.com.pxto.model.Lesson;
import cn.com.pxto.model.LessonType;
import cn.com.pxto.model.School;
import cn.com.pxto.service.GuestManager;
import cn.com.pxto.service.SchoolManager;

public class GuestAction extends DispatchAction {
	private Log log  = LogFactory.getLog(GuestAction.class);
	private SchoolManager schoolManager;
	private GuestManager guestManager;
	
	
	public ActionForward preCreateGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in preCreateGuest method");
		List<School> schoolList=schoolManager.listAllSchool();
		List<LessonType> lessonTypeList=schoolManager.listAllLessonType();
		List<Lesson> lessonList=schoolManager.listALLLesson();
		request.setAttribute("schoolList", schoolList);
		request.setAttribute("lessonTypeList", lessonTypeList);
		request.setAttribute("lessonList", lessonList);
		return mapping.findForward("preCreateGuest");
	}
	
	public ActionForward doCreateGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in doCreateGuest method");
		DynaActionForm guestForm=(DynaActionForm)form;
		Guest guest=(Guest)guestForm.get("guest");
		String startClassTime=request.getParameter("guest.startClassTime");
		if(startClassTime!=null && !startClassTime.equals("")){
			Long temp=StringUtils.dateTimeString2Long(startClassTime);
			guest.setStartClassTime(temp);
		}
		if(guest.getSignType()!=0){
			Integer returnVisitTime=new Integer(request.getParameter("guest.returnVisitTime"));
			Integer importantType=new Integer(request.getParameter("guest.importantType"));
			guest.setImportantType(importantType);
			Long temp=System.currentTimeMillis()+returnVisitTime*24*60*60*1000;
			guest.setReturnVisitTime(temp);
		}else{
			guest.setImportantType(null);
			guest.setReturnVisitTime(null);
		}
		
		LogonInfo logonInfo=(LogonInfo) request.getSession().getAttribute("logonInfo");
		if(logonInfo == null){//没有sessions，则从电话呼叫中获取
//			String cno = (String) request.getSession().getAttribute("cno");
			String cno = (String) request.getParameter("cno");
			Integer uid = new Integer("0");
			try {
				uid = Integer.parseInt(cno);
			} catch (RuntimeException e) {
				System.out.println("cno error ...");
				e.printStackTrace();
			}
			guest.setUserId(uid);
		}else{
			guest.setUserId(logonInfo.getUserId());
		}
		guest.setLogonDate(new Date().getTime());
		guestManager.createGuest(guest);
		String[] strArray=request.getParameterValues("guest.otherSchoolId");
		if(strArray!=null && strArray.length>1){
//			舍去最后一位
			for (int i = 0; i < strArray.length-1; i++) {
				Integer otherSchoolId=new Integer(strArray[i]);
				Guest otherGuest=guest;
				otherGuest.setGid(null);
				otherGuest.setSchoolId(otherSchoolId);
				guestManager.createGuest(otherGuest);
			}
		}
		request.setAttribute("boolean",true);
		return mapping.findForward("success");
	}
	
	public ActionForward preUpdateGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in preUpdateGuest method");
		List<School> schoolList=schoolManager.listAllSchool();
		List<LessonType> lessonTypeList=schoolManager.listAllLessonType();
		List<Lesson> lessonList=schoolManager.listALLLesson();
		request.setAttribute("schoolList", schoolList);
		request.setAttribute("lessonTypeList", lessonTypeList);
		request.setAttribute("lessonList", lessonList);
		int gid=ParamUtil.getIntParams(request, "gid");
		Guest guest=guestManager.getGust(gid);
		request.setAttribute("guest", guest);
		return mapping.findForward("preUpdateGuest");
	}
	
	public ActionForward preReVistGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in preUpdateGuest method");
		List<School> schoolList=schoolManager.listAllSchool();
		List<LessonType> lessonTypeList=schoolManager.listAllLessonType();
		List<Lesson> lessonList=schoolManager.listALLLesson();
		request.setAttribute("schoolList", schoolList);
		request.setAttribute("lessonTypeList", lessonTypeList);
		request.setAttribute("lessonList", lessonList);
		int gid=ParamUtil.getIntParams(request, "gid");
		Guest guest=guestManager.getGust(gid);
		request.setAttribute("guest", guest);
		return mapping.findForward("preReVistGuest");
	}
	
	public ActionForward showGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in showGuest method");
		int gid=ParamUtil.getIntParams(request, "gid");
		Guest guest=guestManager.getGust(gid);
		request.setAttribute("guest", guest);
		return mapping.findForward("showGuest");
	}
	public ActionForward showContact(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in showGuest method");
		int cid=ParamUtil.getIntParams(request, "cid");
		Contact contact = guestManager.getContact(cid);
		request.setAttribute("contact", contact);
		return mapping.findForward("showContact");
	}
	
	public ActionForward doUpdateGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in doUpdateGuest method");
		DynaActionForm guestForm=(DynaActionForm)form;
		Guest guestInForm=(Guest)guestForm.get("guest");
		Guest guest=guestManager.getGust(guestInForm.getGid());
		guest.setSignType(guestInForm.getSignType());
		StringBuffer strBuf = new StringBuffer();
		strBuf.append(guest.getRemark());
		strBuf.append("<br>");
		strBuf.append(guestInForm.getRemark());
		strBuf.append("<br>最近回访时间：");
		strBuf.append(StringUtils.long2TimeString(new Date().getTime()));
		guest.setRemark(strBuf.toString());
		//20090620支持更改联系人名称以及联系人电话
		guest.setTel(guestInForm.getTel());
//		名称不让修改
//		guest.setName(guestInForm.getName());
//		增加最后修改时间
		guest.setModifyDate(new Date().getTime());
		guestManager.updateGuest(guest);
		return listGuest(mapping,form,request,response);
	}
	
	public ActionForward deleteGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in deleteGuest method");
		int gid=ParamUtil.getIntParams(request, "gid");
		guestManager.deleteGuest(gid);
		return listGuest(mapping,form,request,response);
		/*return getGuest(mapping,form,request,response);*/
	}
	
	public ActionForward listGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in listGuest method");
		PageInfo pageInfo=PageUtils.getPageInfo(request);
		LogonInfo logonInfo=(LogonInfo) request.getSession().getAttribute("logonInfo");
		String sort=request.getParameter("sort");
		if(sort == null ){
			sort="logonDate";
		}
		List<Guest> guestList=guestManager.listGuest(logonInfo.getUserId(), sort,pageInfo);
		request.setAttribute("guestList", guestList);
		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("sort", sort);
		return mapping.findForward("listGuest");
	}
	public ActionForward listContact(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in listContact method");
		PageInfo pageInfo=PageUtils.getPageInfo(request);
		LogonInfo logonInfo=(LogonInfo) request.getSession().getAttribute("logonInfo");
		String sort=request.getParameter("sort");
		if(sort == null ){
			sort="cid";
		}
		List<Contact> contactList=guestManager.listContact(logonInfo.getUserId(), sort,pageInfo);
		request.setAttribute("contactList", contactList);
		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("sort", sort);
		return mapping.findForward("listContact");
	}
	/**
	 * 列出回访时间在本周内的联系人（从周日开始，周五结束）
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward listUnSignGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in listUnSignGuest method");
		PageInfo pageInfo=PageUtils.getPageInfo(request);
		LogonInfo logonInfo=(LogonInfo) request.getSession().getAttribute("logonInfo");
		String sort=request.getParameter("sort");
		String value=request.getParameter("value");
		Long startTime=null;
		Long endTime=null;
		Object[] obj=new Object[6];
		int nameType=ParamUtil.getIntParams(request,"nameType");
//		int month=ParamUtil.getIntParams(request, "month");
		Calendar now=Calendar.getInstance();
		switch(nameType){
		case 1:
			obj[3]=value;
			break;
		case 2:
			obj[4]=value;
			break;
		case 3:
			obj[5]=value;
			break;
		}
		startTime=CalendarUtils.getFirstOfWeek(now).getTime();
		endTime=CalendarUtils.getEndOfWeek(now).getTime();		
		if(sort == null ){
			sort="gid";
		}
		obj[0]=startTime;
		obj[1]=endTime;
		obj[2]=logonInfo.getUserId();
//		Object[startTime,endTime,userId,guestName,schoolName,lessonName]
		List<Guest> guestList=guestManager.getWeekGuest(sort,obj,pageInfo);
		request.setAttribute("guestList", guestList);
		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("sort", sort);
		return mapping.findForward("listUnSignGuest");
	}
	
	/**
	 * 列出开课时间在本周内的联系人（从周日开始，周五结束）
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward listWeekClassGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in listWeekClassGuest method");
		PageInfo pageInfo=PageUtils.getPageInfo(request);
		LogonInfo logonInfo=(LogonInfo) request.getSession().getAttribute("logonInfo");
		String sort=request.getParameter("sort");
		String value=request.getParameter("value");
		Long startTime=null;
		Long endTime=null;
		Object[] obj=new Object[6];
		int nameType=ParamUtil.getIntParams(request,"nameType");
//		int month=ParamUtil.getIntParams(request, "month");
		Calendar now=Calendar.getInstance();
		switch(nameType){
		case 1:
			obj[3]=value;
			break;
		case 2:
			obj[4]=value;
			break;
		case 3:
			obj[5]=value;
			break;
		}
		startTime=CalendarUtils.getFirstOfWeek(now).getTime();
		endTime=CalendarUtils.getEndOfWeek(now).getTime();		
		if(sort == null ){
			sort="gid";
		}
		obj[0]=startTime;
		obj[1]=endTime;
		obj[2]=logonInfo.getUserId();
//		Object[startTime,endTime,userId,guestName,schoolName,lessonName]
		List<Guest> guestList=guestManager.getClassGuest(sort,obj,pageInfo);
		request.setAttribute("guestList", guestList);
		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("sort", sort);
		return mapping.findForward("listUnSignGuest");
	}
	
	/**
	 * 重要度回访，列出当前时间以后的回访，并且按最近时间和重要度排序
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward listImportantGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in listWeekClassGuest method");
		PageInfo pageInfo=PageUtils.getPageInfo(request);
		LogonInfo logonInfo=(LogonInfo) request.getSession().getAttribute("logonInfo");
		String value=request.getParameter("value");
		Long startTime=null;
		Long endTime=null;
		Object[] obj=new Object[6];
		int nameType=ParamUtil.getIntParams(request,"nameType");
//		int month=ParamUtil.getIntParams(request, "month");
		Calendar now=Calendar.getInstance();
		switch(nameType){
		case 1:
			obj[3]=value;
			break;
		case 2:
			obj[4]=value;
			break;
		case 3:
			obj[5]=value;
			break;
		}
		startTime=CalendarUtils.getFirstOfWeek(now).getTime();
		endTime=null;		
		obj[0]=startTime;
		obj[1]=endTime;
		obj[2]=logonInfo.getUserId();
//		Object[startTime,null,userId,guestName,schoolName,lessonName]
		List<Guest> guestList=guestManager.getImportantTypeGuest(obj, pageInfo);
		request.setAttribute("guestList", guestList);
		request.setAttribute("pageInfo", pageInfo);
		return mapping.findForward("listImporGuest");
	}
	
	
	public ActionForward getGuest(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in getGuest method");
		PageInfo pageInfo=PageUtils.getPageInfo(request);
		LogonInfo logonInfo=(LogonInfo) request.getSession().getAttribute("logonInfo");
		Long startTime=null;
		Long endTime=null;
		Object[] obj=new Object[8];
		String sort=request.getParameter("sort");
		String value=request.getParameter("value");
//		guestName=1,schoolName=2,lessonName=3
		int nameType=ParamUtil.getIntParams(request,"nameType");
		int month=ParamUtil.getIntParams(request, "month");
		Calendar now=Calendar.getInstance();
		switch(nameType){
		case 1:
			obj[3]=value;
			break;
		case 2:
			obj[4]=value;
			break;
		case 3:
			obj[5]=value;
			break;
//			----===== modify by yoo at 20080426 =====--------
		case 4:
			obj[6]=value;
			break;
//		----===== modify by yoo at 20080426 =====--------	
		case 5:
			obj[7]=value;
			break;
		}
		switch(month){
		case -1:
//			week guest
			//default value is 4
			int revertWeekSize=4;
			try {
				revertWeekSize = Properties.getInstance().getIntValue(
						"revert.week");
			} catch (ConfigurationException e) {
				log.error("get revert.week have error ");
			}
			startTime=now.getTime().getTime()-1000*60*60*24*7*revertWeekSize;
			endTime=now.getTime().getTime()-1000*60*60*24*revertWeekSize;
			break;
		case 13:
//			all
			break;
		default:
			now.set(Calendar.MONTH, month);
			startTime=CalendarUtils.getFirstOfMonth(now).getTime();
			endTime=CalendarUtils.getEndOfMonth(now).getTime();
			break;
		}
		if(sort == null ){
			sort="gid";
		}
		obj[0]=startTime;
		obj[1]=endTime;
		obj[2]=logonInfo.getUserId();
//		Object[startTime,endTime,userId,guestName,schoolName,lessonName,userName]
		List<Guest> guestList=guestManager.getGuest(sort,obj,pageInfo);
		request.setAttribute("guestList", guestList);
		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("sort", sort);

		request.setAttribute("value", value);
		request.setAttribute("nameType", nameType);
		request.setAttribute("month", month);
		return mapping.findForward("getGuest");
	}
	
	public ActionForward getContact(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in getContact method");
		PageInfo pageInfo=PageUtils.getPageInfo(request);
		LogonInfo logonInfo=(LogonInfo) request.getSession().getAttribute("logonInfo");
		Long startTime=null;
		Long endTime=null;
		Object[] obj=new Object[8];
		String sort=request.getParameter("sort");
		String value=request.getParameter("value");
//		guestName=1,schoolName=2,lessonName=3
		int nameType=ParamUtil.getIntParams(request,"nameType");
		int month=ParamUtil.getIntParams(request, "month");
		Calendar now=Calendar.getInstance();
		switch(nameType){
		case 1:
			obj[3]=value;
			break;
		case 2:
			obj[4]=value;
			break;
		case 3:
			obj[5]=value;
			break;
//			----===== modify by yoo at 20080426 =====--------
		case 4:
			obj[6]=value;
			break;
//			----===== modify by yoo at 20080426 =====--------	
		case 5:
			obj[7]=value;
			break;
		}
		switch(month){
		case -1:
//			week guest
			//default value is 4
			int revertWeekSize=4;
			try {
				revertWeekSize = Properties.getInstance().getIntValue(
						"revert.week");
			} catch (ConfigurationException e) {
				log.error("get revert.week have error ");
			}
			startTime=now.getTime().getTime()-1000*60*60*24*7*revertWeekSize;
			endTime=now.getTime().getTime()-1000*60*60*24*revertWeekSize;
			break;
		case 13:
//			all
			break;
		default:
			now.set(Calendar.MONTH, month);
			startTime=CalendarUtils.getFirstOfMonth(now).getTime();
			endTime=CalendarUtils.getEndOfMonth(now).getTime();
			break;
		}
		if(sort == null ){
			sort="cid";
		}
		obj[0]=startTime;
		obj[1]=endTime;
		obj[2]=logonInfo.getUserId();
//		Object[startTime,endTime,userId,guestName,schoolName,lessonName,userName]
		List<Contact> guestList=guestManager.getContact(sort,obj,pageInfo);
		request.setAttribute("contactList", guestList);
		request.setAttribute("pageInfo", pageInfo);
		request.setAttribute("sort", sort);

		request.setAttribute("value", value);
		request.setAttribute("nameType", nameType);
		request.setAttribute("month", month);
		return mapping.findForward("getContact");
	}
	
	/**
	 * 根据呼入的电话判断来访人员信息
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ActionForward listContactOrGuestByTel(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<Object,Object> reqMap =request.getParameterMap();
		Set<Object> keySet = reqMap.keySet();
		for (Object key : keySet) {
			String[] values = (String[])reqMap.get(key) ;
			for (String string : values) {
				System.out.println("after param key :"+(String)key);
				System.out.println("after param value:"+string);
			}
		}
		String cno = request.getParameter("cno");
		String tel = request.getParameter("tel");
		List<Contact> contactList = new ArrayList<Contact>();
		try {
			contactList = guestManager.getContactByTelephone(tel);
			request.setAttribute("contactList", contactList);
		} catch (Exception e) {
			//捕获下错误
			e.printStackTrace();
		}
		if(contactList.size()>0){
			return mapping.findForward("listContactOrGuestByTel");
		}else{//弹出接收保存的页面
			log.info("come in preCreateGuestByTel method");
			List<School> schoolList=schoolManager.listAllSchool();
			List<LessonType> lessonTypeList=schoolManager.listAllLessonType();
			List<Lesson> lessonList=schoolManager.listALLLesson();
			request.setAttribute("schoolList", schoolList);
			request.setAttribute("lessonTypeList", lessonTypeList);
			request.setAttribute("lessonList", lessonList);
			request.setAttribute("tel",tel);//返回电话
			request.setAttribute("cno", cno);//返回客服ID
			return mapping.findForward("preCreateGuestByTel");
		}
	}

	public void setSchoolManager(SchoolManager schoolManager) {
		this.schoolManager = schoolManager;
	}

	public void setGuestManager(GuestManager guestManager) {
		this.guestManager = guestManager;
	}
	
	/*public ActionForward showMyself(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in showMyself method");

		return mapping.findForward("showGuest");
	}
	
	public ActionForward doUpdateMyself(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.info("come in doUpdateMyself method");
		return showMyself(mapping, form, request, response);
	}*/
	

}
